# -*- coding: utf-8 -*-

import re
import time
import base64
import socket
import struct
import hashlib


def ipv42int(k):
    """
    点分格式IPv4地址转十进制格式
    """
    if (isinstance(k, str)):
        k = socket.inet_aton(k)
        k = int(struct.unpack("!L", k)[0])
    return k


def int2ipv4(k):
    """
    十进制IP地址转点分格式IP地址
    """
    k = int(k)
    if (k < 0):
        k = struct.unpack("I", struct.pack("i", k))[0]
    return socket.inet_ntoa(struct.pack("I", socket.htonl(k)))


def ipv62int(k):
    """
    IPv6地址转十进制格式
    """
    k = socket.inet_pton(socket.AF_INET6, k)
    return int.from_bytes(k, byteorder='big')


def oct2hex(k):
    """十六进制转十进制"""
    if (isinstance(k, str)):
        k = hex(int(k))
    return k


def str2hex(k):
    """字符串转十六进制字符串"""
    if (isinstance(k, str)):
        k = k.encode().hex()
    return k


def hex2str(k):
    """十六进制字符串转字符串"""
    if (isinstance(k, str)):
        k = bytes.fromhex(k).decode()
    return k


def time2int(k):
    if (isinstance(k, str)):
        time_formats = [
            '%a, %d %b %Y %H:%M:%S %z (CST)',
            '%a, %d %b %Y %H:%M:%S GMT',
            '%Y-%m-%d %H:%M:%S (UTC)',
            '(0)%b %d, %Y %H:%M:%S.000000000 UTC',
            '(0)%b %d, %Y %H:%M:%S.000000000 %Z',
            '%b %d, %Y %H:%M:%S.000000000 %Z',
            '%a, %d %b, %Y %H:%M:%S %z',
            '%Y-%m-%d %H:%M:%S'
        ]
        for tf in time_formats:
            try:
                return int(time.mktime(time.strptime(k, tf)))
            except OverflowError:  # 1970 8:00 之前的事件转换时会抛出OverflowError异常
                return 0
            except:
                continue
    return k


def str2md5hex(k):
    """
    将字符串转换为md5并转换为十六进制字符串
    :param k:字符串
    :return: 字符串
    """
    if (isinstance(k, str)):
        md5 = hashlib.md5()
        md5.update(k.encode())
        k = md5.hexdigest()
    return k


def science2int(k):
    """
    将科学计数字符串转为整型
    :param k:字符串
    :return: 整型值
    """
    if (isinstance(k, str)):
        if (re.match(r'^\d+\.\d+e\+\d+$', k, re.I)):
            k = int(float(k))
    return k


def base642str(k):
    """
    将Base64字符串转换为字符串 
    :param k:字符串
    :return: 字符串
    """
    k = base64.b64decode(k)
    k = k.decode('utf-8')
    return k
